import React, { Component } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Alert,Form,Button,DatePicker,Select } from 'antd';
import './less/medical.less';
import PTable from "../../../components/Pro/PTable";
import * as request from "../../../utils/request.js";
import * as ajax from "../../../services/api"; //

const { MonthPicker } = DatePicker;
const { Option } = Select;
const monthFormat = 'YYYY-MM';

@connect(state => ({
  global: state.global,
}))

@Form.create()

/**
 * 医社保记录查询
 */
export default class MedicalBasic extends Component {
  constructor(props,context){
    super(props,context);
    // const curDate = new Date();
    // const preDate = new Date(curDate.getTime() - (30 * 24 * 60 * 60 * 1000)); //前一天
    this.state = {
      forceUpdate: false,
      pay: false, //是否设置缴交比例
      payMsg: '',
      comTotalPayAmount:'',//企业缴费总计
      perTotalPayAmount:'',//个人缴费总计
      totalPayAmount:'',//总缴费
      pageParm: {
        paySituation:'3',//缴交情况
        pageSize: "10",
        payPeriod: this.getMonth(),
        pageNumber: "1"
      },
      payPeriod:this.getMonth(), //时间默认值
      paySituation:'3',//缴交情况默认值
    };
  }

  getMonth = () =>{
    const nowdays = new Date();
    let year = nowdays.getFullYear();
    let month = nowdays.getMonth();
    if(month === 0){
        month = 12;
        year--;
    }
    if (month < 10) {
        month = "0" + month;
    }
    const yearMon = year + "-" + month;//上个月的第一天  + "-" + "01"
    return yearMon;
  }

  componentDidMount() {
    this.ajaxGetStaticInfo();
    this.toSetScheme();
  }

  //声明函数 时间选择
  onChangeTime = (date, dateString) =>{
    console.log('dateString' + dateString);
    this.setState({ payPeriod: dateString});
  };

  //声明函数 ajax获取数据，搜索按钮
  getRecList = () => {
    this.ajaxGetStaticInfo(); //获取统计数据
    const pageParm = {...this.state.pageParm};
    pageParm.paySituation = this.state.paySituation;
    pageParm.payPeriod = this.state.payPeriod;
    console.log(">>>>>>>>>>>>>>>>>>>",pageParm);
    this.setState({pageParm,forceUpdate:true}, () => {
      this.setState({forceUpdate: false});
    });
  };

  //头部提醒
  setPay = () =>{
    if(this.state.pay === 0){
      return (
        <div className="medical-head">
          <Alert message={this.state.payMsg} type="warning" showIcon />
          <Button type="primary" className="medical-set" onClick={() => {
            this.props.history.push("/PersonnelRecruitment/proportion");
          }}>去设置</Button>
        </div>
      );
    }else if(this.state.pay === 1){
      return (
        <div className="medical-head">
          <Alert message={this.state.payMsg} type="warning" showIcon />
          <Button type="primary" className="medical-set" onClick={() => {
            this.props.history.push("/PersonnelRecruitment/proportion");
          }}>去设置</Button>
        </div>
      );
    }else{
      return (
        <div className="medical-head"/>
      );
    } //2表示不需要提示
  };

  //ajax 获取统计数据
  ajaxGetStaticInfo = () =>{
    ajax.statHisRecList({
      comId: this.props.global.companyInfo.comId,
      payPeriod: this.state.payPeriod
    }).then((data) => {
      console.log('医社保记录统计' ,data.data);
      if(data.data){
        this.setState({
          totalPayAmount: data.data.totalPayAmount,
          comTotalPayAmount: data.data.comTotalPayAmount,
          perTotalPayAmount: data.data.perTotalPayAmount
        });
      }else{
        this.setState({
          totalPayAmount: 0,
          comTotalPayAmount: 0,
          perTotalPayAmount: 0
        });
      }
    });
  }

  //缴交情况
  handleChangeCondition = (value) => {
    console.log(`selected ${value}`);
    this.setState({ paySituation: value });
  };

  //声明函数 导出excel
  exportList = () => {
    ajax.exportHisRecList({comId:this.props.global.companyInfo.comId,payPeriod:this.state.pageParm.payPeriod}).then((data) => {
      console.log('导出成功',data);
    },(err) => {
      console.log('导出失败',err);
    });
  };

  //提示用户去完成方案的设置
  toSetScheme = () => {
    ajax.promptUserToSetScheme({comId:this.props.global.companyInfo.comId}).then((data) => {
      console.log('提示用户去完成方案的设置' + data.data);
      this.setState({
        pay:data.data,
        payMsg: data.msg
      });
    },(err) => {
      console.log('提示用户去完成方案的设置err',err);
    });
  };

  //PTable 回调函数
  dateTableChange = (data) => {
    console.log('PTable 回调函数',data);
  }

  // 表格渲染
  renderOrderList = () => {
    // const pageInitStudent = {
    //   defaultPageSize: 10,
    //   showQuickJumper: true,
    //   pageSizeOptions: ["5", "10", "15", "20", "25"],
    //   showSizeChanger: true,
    //   showTotal: () => { return '共 ' + this.state.total + ' 条数据';  }
    // };
    const columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
        width: 100,
        fixed: 'left',
      },
      {
        title: '身份证号',
        dataIndex: 'idCardNo',
        key: 'idCardNo',
        width: 180,
        fixed: 'left',
      },
      {
        title: '企业缴交',
        children: [{
          title: '养老保险',
          dataIndex: 'pensionComPayAmount',
          key: 'pensionComPayAmount',
          width: 130,
        },{
          title: '医疗保险',
          dataIndex: 'medicalComPayAmount',
          key: 'medicalComPayAmount',
          width: 130,
        },{
          title: '失业保险',
          dataIndex: 'unemploymentComPayAmount',
          key: 'unemploymentComPayAmount',
          width: 130,
        },{
          title: '工商保险',
          dataIndex: 'injuryComPayAmount',
          key: 'injuryComPayAmount',
          width: 130,
        },{
          title: '生育保险',
          dataIndex: 'birthComPayAmount',
          key: 'birthComPayAmount',
          width: 130,
        }]
      },
      {
        title: '个人缴交',
        children: [{
          title: '养老保险',
          dataIndex: 'pensionPerPayAmount',
          key: 'pensionPerPayAmount',
          width: 130,
        },{
          title: '医疗保险',
          dataIndex: 'medicalPerPayAmount',
          key: 'medicalPerPayAmount',
          width: 130,
        },{
          title: '失业保险',
          dataIndex: 'unemploymentPerPayAmount',
          key: 'unemploymentPerPayAmount',
          width: 130,
        },{
          title: '工商保险',
          dataIndex: 'injuryPerPayAmount',
          key: 'injuryPerPayAmount',
          width: 130,
        },{
          title: '生育保险',
          dataIndex: 'birthPerPayAmount',
          key: 'birthPerPayAmount',
          width: 130,
        }]
      },
      {
        title: '合计',
        dataIndex: 'totalPayAmount',
        key: 'totalPayAmount',
        width: 130,
        fixed: 'right',
      }
    ];


    return (
      <PTable
        columns={columns}
        url="getHisRecListPage"
        pageParm={this.state.pageParm}
        dateChange={this.dateTableChange}
        // scroll={{ x:'200%',}}
        scroll={{ x: 1800 }}
        forceUpdate={this.state.forceUpdate}
        showTotal
      />
    );
  };

  render() {
    return (
      <div className="medical">
        {this.setPay()}
        <div className="medical-chearch">
          <label>缴费年月：
            <MonthPicker
              format={monthFormat}
              defaultValue={moment(this.state.pageParm.payPeriod, monthFormat)}
              onChange={this.onChangeTime}
              placeholder="请选择年月"
              allowClear={false}
            />
          </label>
          <label style={{ marginLeft: '16px' }}>缴交情况：</label>
            <Select
              showSearch
              style={{ width: 214 }}
              optionFilterProp="children"
              placeholder="请选择"
              onChange={this.handleChangeCondition}
              defaultValue={this.state.paySituation}
            >
              <Option value="1">未缴费人员</Option>
              <Option value="2">已缴费人员</Option>
              <Option value="3">全部人员</Option>
            </Select>
          <Button style={{marginLeft:16}} type="primary" onClick={this.getRecList}>搜索</Button>
        </div>
        <div className="medical-content">
          <span>{this.state.pageParm.payPeriod}</span>|<span>应缴交总计</span><span className="span-blue">{this.state.totalPayAmount}元</span>|
          <span>企业缴交总金额</span><span className="span-blue">{this.state.comTotalPayAmount}元</span>|
          <span>个人缴交总金额</span><span className="span-blue">{this.state.perTotalPayAmount}元</span>
        </div>
        <div className="medical-link" style={{marginBottom:'10px'}}>
          <Button type="primary" style={{marginRight:'8px'}} onClick={() => window.open(request.getHostByPath('/enterprise') + '/enterprise/ins/medical-social-rec/export-his-rec-list?comId=' + this.props.global.companyInfo.comId + '&payPeriod=' + this.state.pageParm.payPeriod, "_self",)}>导出excel</Button>
          {/* {console.log(request.getHostByPath('/enterprise') + '/enterprise/ins/medical-social-rec/export-his-rec-list?comId=' + this.state.pageParm.comId + '&payPeriod=' + this.state.pageParm.payPeriod)} */}
          <Button onClick={() => {
            this.props.history.push("/PersonnelRecruitment/proportion");
          }}>缴费比例管理</Button>
        </div>
        { this.renderOrderList() }
      </div>
    );
  }
}



